﻿import { ref, h, createApp } from 'vue';
import { ElDialog, ElButton } from 'element-plus';
import i18n from '@/lang';
import myRouter from '@/router';
/**
 *
 * @param component 组件模板
 * @param props 组件的属性
 * @param dialogProps  ElDialog的属性
 */
export const openDialog = (component: any, props: any, dialogProps: any) => {
    const open = ref(true);
    const isLoading = ref(false);
    const instance = ref();
    const dialog = () =>
        h(
            ElDialog,
            {
                ...dialogProps,
                modelValue: true,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                onClosed: () => {
                    unmount();
                },
            },
            {
                default: () => h(component, { ...props, ref: instance, unmount }),
                footer: () =>
                    dialogProps?.footer &&
                    h('div', [
                        h(
                            ElButton,
                            {
                                onClick: () => {
                                    unmount();
                                },
                            },
                            () => dialogProps.cancleName || '取消'
                        ),
                        h(
                            ElButton,
                            {
                                type: 'primary',
                                loading: isLoading.value,
                                onClick: async () => {
                                    try {
                                        isLoading.value = true;
                                        await instance?.value?.onSubmit();
                                        unmount();
                                    } catch (err) {
                                        console.log(err);
                                    } finally {
                                        isLoading.value = false;
                                    }
                                },
                            },
                            () => dialogProps.submitName || '确认'
                        ),
                    ]),
            }
        );
    // 挂载
    const app = createApp(dialog);
    app.use(i18n).use(myRouter);
    const div = document.createElement('div');
    document.body.appendChild(div);
    app.mount(div);
    // 卸载
    function unmount() {
        open.value = false;
        app.unmount();
        document.body.removeChild(div);
    }

    return {
        instance,
        unmount,
    };
};
